/**
 * 证书辅助工具
 * 用于在签名、加密等功能中自动获取已识别的证书
 */

export interface CertificateInfo {
  index: number;
  subjectCN: string;
  issuerCN: string;
  certSN: string;
  validFrom: string;
  validTo: string;
  algorithm: string;
  usage: string;
  keyIndex: number;
}

/**
 * 获取自动识别的证书列表
 */
export function getAutoDetectedCerts(): CertificateInfo[] {
  const certs = (window as any).g_AutoDetectedCerts;
  if (!certs || !Array.isArray(certs)) {
    console.warn('⚠️ 未找到自动识别的证书，请先插入介质');
    return [];
  }
  return certs;
}

/**
 * 获取签名证书
 */
export function getSignCert(): CertificateInfo | null {
  const certs = getAutoDetectedCerts();
  const signCert = certs.find(cert => cert.usage === '签名');
  
  if (signCert) {
    console.log('✓ 自动获取签名证书:', signCert.subjectCN);
    return signCert;
  }
  
  console.warn('⚠️ 未找到签名证书');
  return null;
}

/**
 * 获取加密证书
 */
export function getEncryptCert(): CertificateInfo | null {
  const certs = getAutoDetectedCerts();
  const encryptCert = certs.find(cert => cert.usage === '加密');
  
  if (encryptCert) {
    console.log('✓ 自动获取加密证书:', encryptCert.subjectCN);
    return encryptCert;
  }
  
  console.warn('⚠️ 未找到加密证书');
  return null;
}

/**
 * 获取原始证书对象（用于调用ZJCA SDK）
 */
export function getRawCertList(): any[] {
  const certList = (window as any).g_CurrentCertList;
  if (!certList || !Array.isArray(certList)) {
    console.warn('⚠️ 未找到证书对象列表');
    return [];
  }
  return certList;
}

/**
 * 根据用途获取原始证书对象
 */
export function getRawCertByUsage(usage: 'sign' | 'encrypt'): any | null {
  const certList = getRawCertList();
  const targetUsage = usage === 'sign' ? 1 : 2;
  
  const cert = certList.find((c: any) => {
    const certUsage = c.getUsage ? c.getUsage() : 0;
    return certUsage === targetUsage;
  });
  
  if (cert) {
    const subjectCN = cert.getSubjectCN ? cert.getSubjectCN() : '未知';
    console.log(`✓ 找到${usage === 'sign' ? '签名' : '加密'}证书:`, subjectCN);
    return cert;
  }
  
  console.warn(`⚠️ 未找到${usage === 'sign' ? '签名' : '加密'}证书`);
  return null;
}

/**
 * 检查是否有可用的证书
 */
export function hasCertificates(): boolean {
  const certs = getAutoDetectedCerts();
  return certs.length > 0;
}

/**
 * 获取证书摘要信息（用于UI显示）
 */
export function getCertsSummary(): string {
  const certs = getAutoDetectedCerts();
  
  if (certs.length === 0) {
    return '未识别到证书';
  }
  
  return certs.map(c => `${c.subjectCN}(${c.usage})`).join(' / ');
}

